<?php

namespace web\common\command;

use addons\member\model\MemberAccountModel;
use web\common\model\sys\SysParameterModel;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\input\Argument;
use think\console\Output;
use think\Exception;
use think\Db;

class Fix extends Command{

    /**
     * 定义命令
     */
    protected function configure(){
        $this->setName('Fix')->setDescription('RUN ETH Data RPC API');
        $this->addArgument('action', Argument::REQUIRED, "The name of the function");
        //参数2
        $this->addArgument('param', Argument::OPTIONAL, "The name of the param");
    }
    
    protected function execute(Input $input, Output $output) {
        $action = $input->getArgument('action');
        $param = $input->getArgument('param');
        if (method_exists($this,$action)) {
            $this->$action($param);
        }
        else{
            echo "method is not exists\n";
        }
    }

    public function test(){
        $userM = new \addons\member\model\MemberAccountModel();
        $count = $userM->getPushTotal(100627034);
        dump($count);

    }

    /**
     * 强制过期
     */
    public function equipPass(){
        $userM = new \addons\member\model\MemberAccountModel;
        $orderM = new \addons\equip\model\EquipOrder;
        $equip_data = (new \addons\equip\model\Equip)->column('id,guide_value,send_active,exchange_amount');
// 100628189
// 100628193
        // $list = $userM->field('id')->where(['id'=>['in',[100628176,100628189,100628193]]])->limit(0,1000)->select();
        $list = $userM->field('id')->where(['pid_path'=>['like','%100627074%']])->limit(0,1000)->select();
        // dd($list);
        $phyM = new \addons\member\model\PhysicalContribution;
        foreach ($list as $k => $v) {
            $e_list = $orderM->field('id,e_id,status,user_id')->where(['user_id'=>$v['id'],'status'=>0])->select();
            $this->equipToPass($e_list,$equip_data,$orderM,$phyM,$userM);
            echo $v['id']."|success\n";
        }
    }


    /**
     * 强制过期
     */
    public function equipDoing(){
        $userM = new \addons\member\model\MemberAccountModel;
        $orderM = new \addons\equip\model\EquipOrder;
        $equip_data = (new \addons\equip\model\Equip)->column('id,guide_value,send_active,exchange_amount');
        // $list = $userM->field('id')->where(['id'=>['in',[100628176,100628189,100628193]]])->limit(0,1000)->select();
        $list = $userM->field('id')->where(['pid_path'=>['like','%100627074%']])->limit(0,1000)->select();
        // dd($list);
        $phyM = new \addons\member\model\PhysicalContribution;
        foreach ($list as $k => $v) {
            $e_list = $orderM->query("UPDATE `tp_equip_order`  SET `update_time`='".NOW_DATETIME."',`status`=0  WHERE  `user_id` = ".$v['id']."  AND `status` = 1  AND `e_id` = 1 and `total_reward` >`total_release`");
            // $e_list = $orderM->field('id,e_id,status,user_id')->where(['user_id'=>$v['id'],'status'=>1,'e_id'=>['>',1]])->update(['update_time'=>NOW_DATETIME,'status'=>0]);
            // $this->equipToDoing($e_list,$equip_data,$orderM,$phyM,$userM);
            echo $v['id']."|success\n";
        }
    }

    public function equipToDoing($list,$equip_data,$orderM,$phyM,$userM){
        foreach ($list as $key => $v) {
            $orderM->startTrans();
            $res = $orderM->where('id',$v['id'])->update(['update_time'=>NOW_DATETIME,'status'=>0]);
            if(!$res){
                $balanceM->rollback();
                continue;
            }
            $orderM->commit();
        }

    }

    public function equipToPass($list,$equip_data,$orderM,$phyM,$userM){
        foreach ($list as $key => $v) {
            $orderM->startTrans();
            $res = $orderM->where('id',$v['id'])->update(['update_time'=>NOW_DATETIME,'status'=>1]);
            if(!$res){
                $balanceM->rollback();
                continue;
            }
            // //团队业绩
            // $res = $phyM->teamStrengthCal($v['user_id'],$equip_data[$v['e_id']]['exchange_amount'],$equip_data[$v['e_id']]['send_active'],0);
            // if(!$res){
            //     $balanceM->rollback();
            //     continue;
            // }
            // $count = $orderM->where(['user_id'=>$v['user_id'],'status'=>0])->count();
            // if($count==0){
            //     //团队业绩
            //     $pid_path = $userM->where('id',$v['user_id'])->value('pid_path');
            //     $res = $phyM->addPhy($pid_path,-50,3);
            //     if(!$res){
            //         $balanceM->rollback();
            //         continue;
            //     }
            // }
            $orderM->commit();
        }

    }
    
    /**
     * 修复贡献值
     */
    public function fixCom(){
        $userM = new \addons\member\model\MemberAccountModel();
        $map = [];
        $phyM = new \addons\member\model\PhysicalContribution();
        $orderM = new \addons\equip\model\EquipOrder;
        $page = 0;
        $rows = 100;
        $list = $phyM->field('user_id,push_total,push_auth_total,com')->where($map)->order('user_id desc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        while ($list) {
            foreach ($list as $k => $v) {
                $user_id = $v['user_id'];
                echo "$user_id \n";
                $ids = $userM->where('pid',$user_id)->column('id');
                $count = $orderM->where(['user_id'=>['in',$ids],'status'=>0])->group('user_id')->count();
                // $sum = $phyM->where(['user_id'=>['in',$ids]])->sum('com');
                $phyM->where('user_id',$user_id)->update(['com'=>$count*50]);
            }
            $page++;
            echo "page:{$page} \n";
            // $list = [];
            $list = $phyM->field('user_id,push_total,push_auth_total,com')->where($map)->order('user_id desc')->limit($page*$rows,$rows)->select();
            // $list = $userM->field('id,pid_path')->order('id asc')->limit($page*100,100)->select();
        }
        echo "fix done \n";
    }


    /**
     * 修复业绩与贡献值 从大到小
     */
    public function fixActivity(){
        $equip_data = (new \addons\equip\model\Equip)->column('id,exchange_amount,send_active');
        $map = [];
        $phyM = new \addons\member\model\PhysicalContribution();
        $save_data = [
            'team_strength'=>0,
            'activity'=>0,
            'signle_team'=>0,
            'single_activity'=>0,
        ];
        $phyM->where('1=1')->update($save_data);
        $page = 0;
        $rows = 100;
        $orderM = new \addons\equip\model\EquipOrder;
        $map['status'] = 0;
        $map['create_time'] = ['<',NOW_DATETIME];
        $list = $orderM->field('user_id,e_id')->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        while ($list) {
            foreach ($list as $k => $v) {
                $user_id = $v['user_id'];
                $amount = $equip_data[$v['e_id']]['exchange_amount'];
                $send_active = $equip_data[$v['e_id']]['send_active'];
                $res = $phyM->teamStrengthCal($user_id,$amount,$send_active,1);
            }
            $page++;
            echo "page:{$page} \n";
            $list = $orderM->field('user_id,e_id')->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        }
        echo "fix done \n";
    }

    /**
     * 计算活跃值
     */
    public function calAct(){
        $userM = new \addons\member\model\MemberAccountModel();
        $list = $userM->where(['pid_path'=>['like','%,100627040,%']])->column('id');
        $equip_data = (new \addons\equip\model\Equip)->column('id,exchange_amount,send_active');
        $orderM = new \addons\equip\model\EquipOrder;
        $order_list = $orderM->field('e_id')->where(['user_id'=>['in',$list]])->select();
        $total = 0;
        foreach ($order_list as $key => $v) {
            $total += $equip_data[$v['e_id']]['send_active'];
        }
        dump($total);
    }

    /**
     * 修复推荐数量
     */
    public function fixPushTotal(){
        $userM = new \addons\member\model\MemberAccountModel();
        $map = [];
        $phyM = new \addons\member\model\PhysicalContribution();
        $page = 0;
        $rows = 100;
        $list = $phyM->alias('p')->join('member_account m','m.id=p.user_id')->field('user_id,push_total,push_auth_total')->where($map)->order('user_id desc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        while ($list) {
            foreach ($list as $k => $v) {
                $user_id = $v['user_id'];
                echo "$user_id \n";
                $count = $userM->getPushTotal($user_id);
                // $count = $this->getAuthids($user_id);
                // $count = $this->getids($user_id);
                $phyM->where('user_id',$user_id)->update(['push_total'=>$count]);
                // $phyM->where('user_id',$user_id)->update(['push_auth_total'=>$count]);
            }
            $page++;
            echo "page:{$page} \n";
            // $list = [];
            $list = $phyM->alias('p')->join('member_account m','m.id=p.user_id')->field('user_id,push_total,push_auth_total')->where($map)->order('user_id desc')->limit($page*$rows,$rows)->select();
            // $list = $phyM->field('user_id,push_total,push_auth_total')->where($map)->order('user_id desc')->limit($page*$rows,$rows)->select();
            // $list = $userM->field('id,pid_path')->order('id asc')->limit($page*100,100)->select();
        }
        echo "fix done \n";
    }

    /**
     * 修复推荐数量
     */
    public function fixAmount(){
        $userM = new \addons\member\model\MemberAccountModel();
        $map = [];
        $balanceM = new \addons\member\model\Balance();
        $field = 'id';
        $page = 0;
        $rows = 100;
        $list = $userM->field($field)->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        $coin_type = 3;
        while ($list) {
            foreach ($list as $k => $v) {
                $ex = $balanceM->where(['user_id'=>$v['id'],'type'=>$coin_type])->value('id');
                if($ex) continue;
                $balance = array(
                    'user_id' => $v['id'],
                    'type' => $coin_type,
                    'update_time' => NOW_DATETIME,
                );
                $res = $balanceM->add($balance);
            }
            $page++;
            echo "page:{$page} \n";
            // $list = [];
            $list = $userM->field($field)->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        }
        echo "fix done \n";
    }


    /**
     * 修复数量 从大到小
     */
    public function fixNumber(){
        $userM = new \addons\member\model\MemberAccountModel();
        $map = [];
        $phyM = new \addons\member\model\PhysicalContribution();
        $page = 0;
        $rows = 100;
        $list = $phyM->alias('p')->join('member_account m','m.id=p.user_id','left')->field('user_id,push_total,push_auth_total')->where($map)->order('deep desc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        while ($list) {
            foreach ($list as $k => $v) {
                $user_id = $v['user_id'];
                echo "$user_id \n";
                $count = $userM->getPushTotal($user_id);
                $phyM->where('user_id',$user_id)->update(['push_total'=>$count]);
            }
            $page++;
            echo "page:{$page} \n";
            $list = $phyM->alias('p')->join('member_account m','m.id=p.user_id','left')->field('user_id,push_total,push_auth_total')->where($map)->order('deep desc')->limit($page*$rows,$rows)->select();
        }
        echo "fix done \n";
    }


    /**
     * 修复数量 从大到小
     */
    public function fixPhy(){
        $userM = new \addons\member\model\MemberAccountModel();
        $map = [];
        $phyM = new \addons\member\model\PhysicalContribution();
        $page = 0;
        $rows = 100;
        $list = $userM->field('id,is_auth')->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        echo "in list \n";
        while ($list) {
            foreach ($list as $k => $v) {
                $phyM->createPhy($v['id']);
            }
            $page++;
            echo "page:{$page} \n";
            $list = $userM->field('id,is_auth')->where($map)->order('id asc')->limit($page*$rows,$rows)->select();
        }
        echo "fix done \n";
    }


    public function fixParent($user_id=''){
        $userM = new \addons\member\model\MemberAccountModel();
        if($user_id!=''){
            $ids = $userM->getPids($user_id);
            $new = explode(',', $ids);
            krsort($new);
            $deep = count($new);
            $ids = implode(',', $new);
            $ids = ','.$ids.',';
            $res = $userM->where('id',$user_id)->update(['pid_path'=>$ids,'deep'=>$deep]);
            if($res){
                echo "success done \n";
            }else{
                echo "fail done \n";
            }
        }else{
            $rows = 100;
            $list = $userM->field('id,pid_path')->order('id desc')->limit(0,$rows)->select();
            $page = 0;
            echo "in list \n";
            while ($list) {
                foreach ($list as $k => $v) {
                    $user_id = $v['id'];
                    echo "user_id:{$user_id}\n";
                    $ids = $userM->getPids($user_id,'',1);
                    $new = explode(',', $ids);
                    // krsort($new);
                    $deep = count($new);
                    if($deep==80){
                        $new = array_unique(array_filter(explode(',', $ids)));
                        $deep = count($new);
                    }
                    $ids = implode(',', $new);
                    $ids = ','.$ids.',';
                    if($v['pid_path']==$ids){
                        continue;
                    }
                    $res = $userM->where('id',$user_id)->update(['pid_path'=>$ids,'deep'=>$deep]);
                }
                $page++;
                echo "page:{$page} \n";
                $list = $userM->field('id,pid_path')->order('id desc')->limit($page*$rows,$rows)->select();
            }
            echo "fix done \n";
        }
    }


    /**
     * 每4小时获取美元人民币汇率
     * @return float
     */
    function updateUsdt(){
        $url = 'http://op.juhe.cn/onebox/exchange/currency';
        $data = [
            'from' => 'usd',
            'to' => 'cny',
            'key' => '3c32260c0b0a9b536ce32e67d7e8eded',
        ];
        $output = http($url, $data);
        echo $output['data']['result'][0]['exchange'];
        (new \web\common\model\sys\SysParameterModel())->where(['field_name' => 'usdt_price'])->update(['parameter_val' => $output['data']['result'][0]['exchange']]);
        echo '--ok';
    }


    /**
     * 中币usdt单价
     */
    public function zbUsdt(){
        $url = "http://api.zb.live/data/v1/ticker?market=usdt_qc";
        $res = http($url);
        if(isset($res['data']['ticker']['last'])){
            (new \web\common\model\sys\SysParameterModel())->where(['field_name' => 'usdt_price'])->update(['parameter_val' => $res['data']['ticker']['last']]);
        }
    }



    /**
     * 更新ETH USDT价格
     */
    public function updatePrice(){
        $res = http('https://fxhapi.feixiaohao.com/public/v1/ticker');
        if(isset($res['data'])){
            foreach ($res['data'] as $key => $value) {
                if($value['symbol']=='ETH'){
                    (new SysParameterModel())->where('field_name','eth_price')->update(['parameter_val'=>$value['price_usd']]);
                }
            }
        }
        $res = http('http://api.zb.live/data/v1/ticker?market=usdt_qc');
        if(isset($res['data'])){
            (new SysParameterModel())->where('field_name','usdt_price')->update(['parameter_val'=>$res['data']['ticker']['last']]);
        }
    }

  
}